package org.offsync.util

trait Disposable {
  def disposeState: DisposeState
  
  def dispose(): Unit
  
  def waitDisposed(
      deadline: Time = Never): Unit
  
  def auto[T](f: AutoDisposed[this.type] => T): T = {
    val disposable = new AutoDisposed[this.type](this)
    try {
      f(disposable)
    } finally {
      disposable.dispose()
    }
  }
  
  def using[U](f: this.type => U): U = try f(this) finally this.dispose()
}

object Disposed extends Disposable {
  override def disposeState = DisposeState.Disposed
  
  override def dispose(): Unit = { }
  
  override def waitDisposed(
      deadline: Time): Unit = { }
}
